package 中等.从前序与中序序列遍历构造二叉树;

import java.util.HashMap;

//递归
public class Solution1 {
    private HashMap<Integer,Integer> map;
    public TreeNode myBuildTree(int[] preorder,int[] inorder,int preorder_left,int preorder_right,int inorder_left,int inorder_right){

        if(preorder_left > preorder_right){
            return null;
        }
        //从前序遍历获取根节点
        int preorder_root = preorder_left;
        //中序遍历中获取根节点的位置
        int inorder_root = map.get(preorder[preorder_root]);

        //把根节点建立出来
        TreeNode root = new TreeNode(preorder[preorder_root]);

        //获取中序遍历从头结点开始到尾结点中间左节点的个数
        int num_inorder_left = inorder_root - inorder_left;

        //遍历左子树
        root.left = myBuildTree(preorder,inorder,preorder_left+1,preorder_left+num_inorder_left,inorder_left,inorder_root-1);
        //遍历右子树
        root.right = myBuildTree(preorder,inorder,preorder_left+num_inorder_left+1,preorder_right,inorder_root+1,inorder_right);
        return root;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int n = inorder.length;
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i],i);
        }
        return  myBuildTree(preorder,inorder,0,n-1,0,n-1);
    }
}
